// GLOBALS

var lastname = '';
var curCase = '';
var myLayout = '';



/* * * * 
 * LOG *
 * * * */

function clearLOG() { $('#LOG').empty(); }

function writeLOG(msg){
	var d = new Date()
	$('#LOG').prepend('<span><b>['+ d.getDate() +'/'+ (d.getMonth()+1) +'/'+ d.getFullYear() + ' ' + d.toLocaleTimeString() + ']</b>: ' + msg + '</span><br/>');
	if($('#LOG SPAN').length > 100) $('#LOG').remove();
}

/* * * * *
 * HMENU *
 * * * * */

function hmenu(){
	$(" #nav ul ").css({display: "none"}); // Opera Fix
	$(" #nav li").hover(function(){
		$(this).find('ul:first').css({visibility: "visible",display: "none"}).show(400);
	},function(){
		$(this).find('ul:first').css({visibility: "hidden"});
	});
}


/* * * * *
 * QUEUE *
 * * * * */

function showQueue(){
	writeLOG('Loading queue...');
	$.post("index.php", {mod: "queueManager", action: "show"}, function(msg){ 
		$("#queueList").html(msg);
		return 1;
	});
	writeLOG('Queue Loaded!');
}


/* * * * * *
 * LOG OUT *
 * * * * * */

function logout(){
	writeLOG('Loging out...');
	$.post("index.php", {mod: "auth", action: "logout"},function(msg){
		self.location = msg;
	});
	writeLOG('Logued out!');
}

/* * * * * *
 * DIALOGS *
 * * * * * */
 
function loadCaseManager(){
	// Loads caseManager
	$.post("index.php", {mod: 'caseManager'}, function(res) {
		$("#dialog").html(res);
		$("#dialog").dialog({
			title: 'Gestión de casos',
			bgiframe: true,
			modal: true,
			width: 700,
			height: 350,
			closeOnEscape: false,
			close: function() {
				$(this).dialog("destroy");
			}
		});
   	});
}

function loadScriptManager(itemlist){
	// Loads caseManager
	$.post("index.php", {mod: 'scriptManager', items: itemlist}, function(res) {
		$("#dialog").html(res);
		$("#dialog").dialog({
			title: 'Scripts de extracción de información',
			bgiframe: true,
			modal: true,
			width: 600,
			height: 350,
			closeOnEscape: false,
			close: function() {
				$(this).dialog("destroy");
			},
			buttons: {
				Cancel: function() {
					$(this).dialog('close');
				},
				Extraer: function() {
					var n = $("#dialog").find("input:checked").length;
					if (n == 0){
						alert("Debes seleccionar algún script.");
					} else {
						var sc="";
						$("#dialog").find("input:checked").each(function(){
							sc+=$(this).val() + "+";
						});
						$.post("index.php", {mod: 'queueManager', action: "add", scripts: sc, items: itemlist}, function(){
							showQueue();
						});
						
						$(this).dialog('close');
					}
				}
			},
		});
   	});
}



/* * * * *
 * TREES *
 * * * * */

function casetree() { 
	$("#casetree").tree({
		types: {
			"defaults": {
				draggable: false,
			},
			"cases": {
				deletable: false,
				renameable: false,
			},
			"case": {
				max_depth: 3,
				icon : {
					image : "images/case.png"
				}
			},
			"device": {
				max_depth: 2,
				renameable: false,
				icon : {
					image : "images/device.png"
				}
			},
			"disk": {
				max_depth: 1,
				creatable: false,
				renameable: false,
				icon : {
					image : "images/disk.png"
				}
			},
			"partition": {
				draggable: false,
				creatable: false,
				renameable: false,
				deletable: false,
				icon : {
					image : "images/partition.png"
				}
			}
		},
		data: {
			async : true,
			opts: {
				method: "POST",
				url : "index.php"
			}
		},
		callback: {
			beforedata: function(n, t){
				return { mod: 'caseManager', action: 'tree', item: t.get_text(n) };
			},
			onselect: function(n, t){
				if (t.get_type(n) == "case"){
					$('#dialog').dialog('option', 'buttons', { "Comenzar": function() { 
						$.post("index.php", {mod: 'caseManager', action: 'set', 'case': t.get_text(n)}, function(){
							showQueue();
						});
						devtree(t.get_text(n));
						$(this).dialog("destroy"); 
					}});
				} else {
					$('#dialog').dialog('option', 'buttons', { });
				}

				$.post("index.php", {mod: 'caseManager', action: 'info', item: t.get_text(n)}, function(msg){ 
					$("#caseinfo").html(msg);
					return 1;
				});

			},
			oncreate: function(n,rn,t,tr,rb){
				if (tr.get_type(n) == "device"){ tr.set_type("disk",n); }
				if (tr.get_type(n) == "case"){ tr.set_type("device",n);	}
				if (tr.get_type(n) == "cases"){ tr.set_type("case",n); }
				
				$.ajax({
					url: "index.php",
					type: 'POST',
					data: {mod: 'caseManager', action: 'add', to: tr.parent(n).children("a").text()},
					async: false,
					cache: false,
					timeout: 3000000,
					error: function(){
						return true;
					},
					success: function(msg){ 
						//$(n).children("a").attr("rel",msg);
						$(n).children("a").html("<ins>&nbsp;</ins>" + msg);
						return 1;
					}
				});

				// mando peticion y refresco arbol
			},
			beforerename: function(n,l,t){
				lastname = t.get_text(n);
				return true;
			},
			onrename: function(n,t,rb){
				$.post("index.php", {mod: 'caseManager', action: 'ren', last: lastname, name: t.get_text(n)});
				lastname = '';
			},
			beforedelete: function(n,t){
				if(confirm("¿Seguro que quieres eliminar este item ("+t.get_text(n)+")?")) {
					return true;
				} else {
					return false;
				}
			},
			ondelete: function(n,t,rb){
				$.post("index.php", {mod: 'caseManager', action: 'del', name: t.get_text(n)});
			},
		},
		ui : {
			theme_name : "apple"
		},
		plugins : {
//			checkbox : { },
			contextmenu: { },
		}
	});
}

function devtree(c){
	if (c != ''){
		curCase=c;
	}
	$("#devtree").tree({
		rules: {
			multiple: "on",
		},
		types: {
			"device": {
				draggable: false,
				creatable: false,
				renameable: false,
				deletable: false,
				icon : {
					image : "images/device.png"
				}
			},
			"disk": {
				draggable: false,
				creatable: false,
				renameable: false,
				deletable: false,
				icon : {
					image : "images/disk.png"
				}
			},
			"partition": {
				draggable: false,
				creatable: false,
				renameable: false,
				deletable: false,
				icon : {
					image : "images/partition.png"
				}
			}
		},
		data: {
			async : true,
			opts: {
				method: "POST",
				url : "index.php"
			}
		},
		callback: {
			beforedata: function(n, t){
				i = t.get_text(n);
				if ( i == ''){
					i = curCase;
				}
				return { mod: 'caseManager', action: 'tree', item: i };
			},
			onselect: function(n, t){
				// Si no está montado lo monto
				return 1;
			},
			onchange: function(n, t){
				//$("#results")
				//alert(t.get_text(n));
				return 1;
			},
		},
		ui : {
			theme_name : "apple"
		},
		plugins : {
//			checkbox : { },
			contextmenu: {
				items : {
					// get rid of the remove item
					create: false,
					rename: false,
					remove: false,
					// add an item of our own
					use: {
						label	: "Usar", 
						icon	: "./images/info.png",
						action	: function (n, t) {
							var nodes='';
							for(var i in t.selected_arr){
								nodes+=t.get_text(t.selected_arr[i])+"+";
							}
							nodes+=t.get_text(n);
							loadResultsTree(nodes);
							//alert(t.get(n, "xml_nested", false)); 
						},
						separator_before : true,
					},
					info: {
						label	: "Información", 
						icon	: "./images/info.png",
						visible	: function (n, t) { 
							// this action will be disabled if more than one node is selected
							if(n.length != 1) return 0; 
							// this action will not be in the list if condition is met
							//if(t.get_text(n) == "Child node 1") return -1; 
							// otherwise - OK
							return 1; 
						}, 
						action	: function (n, t) {
							$.post("index.php", {mod: 'caseManager', action: 'info', item: t.get_text(n)}, function(msg){ 
								$("#information").html(msg);
								return 1;
							});
							myLayout.open('east');
							//alert(t.get(n, "xml_nested", false)); 
						},
						separator_before : true,
					},
					extract: {
						label	: "Extraer...", 
						icon	: "./images/info.png",
						action	: function (n, t) {
							var nodes='';
							for(var i in t.selected_arr){
								nodes+=t.get_text(t.selected_arr[i])+"+";
							}
							nodes+=t.get_text(n);
							loadScriptManager(nodes);
							//alert(t.get(n, "xml_nested", false)); 
						},
						separator_before : true,
					},
				},
			},
		}
	});
}

function loadResultsTree(nodes){
	$("#results").tree({
		types: {
			"default": {
				draggable: false,
				creatable: false,
				renameable: false,
				deletable: false,
			},
		},
		data: {
			opts: {
				method: "POST",
				url : "index.php"
			}
		},
		callback: {
			beforedata: function(n, t){
				if (nodes){
					return { mod: 'results', items: nodes };
				} else {
					alert("A");
				}
			},
			onselect: function(n, t){
				// Si no está montado lo monto
				return 1;
			},
		},
		ui : {
			theme_name : "apple"
		},
		plugins : {
			contextmenu: {
				items : {
					// get rid of the remove item
					create: false,
					rename: false,
					remove: false,
					// add an item of our own
					bookmark: {
						label	: "Bookmark...", 
						icon	: "./images/bookmarks.png",
						action	: function (n, t) {
							alert("Wait for it... ("+t.get_text(n)+")");
							//alert(t.get(n, "xml_nested", false)); 
						},
					},
					info: {
						label	: "Información", 
						icon	: "./images/info.png",
						visible	: function (n, t) { 
							// this action will be disabled if more than one node is selected
							if(n.length != 1) return 0; 
							// this action will not be in the list if condition is met
							if(t.get_text(n) == "Allocated" || t.get_text(n) == "Deleted") return -1; 
							// otherwise - OK
							return 1; 
						}, 
						action	: function (n, t) {
							var c = $(n).find("label").attr("class");
							if ( c == "device" || c == "disk" || c == "partition"){
								$.post("index.php", {mod: 'caseManager', action: 'info', item: t.get_text(n)}, function(msg){ 
									$("#information").html(msg);
									return 1;
								});
							} else {
								var p = '';
								$(n).parents().each(function () { 
									if ($(this).find("label").attr("class") == "partition"){
										p = $(this).children("a").html();
										return false;
									}
								});
								$.post("index.php", {mod: 'file', action: 'info', inode: $(n).find("label").attr("rel"), part: p}, function(msg){ 
									$("#information").html(msg);
									return 1;
								});
							}
							myLayout.open('east');
							//alert(t.get(n, "xml_nested", false)); 
						},
						separator_before : true,
					},
					ImageBrowser: {
						label	: "Ver Imágenes", 
						icon	: "./images/imagebrowser.png",
						action	: function (n, t) {
							var base = '';
							var c = $(n).find("label").attr("class");
							if ( c == "device" || c == "disk" || c == "partition"){
								base = t.get_text(n);
							} else {
								$(n).parents().each(function () { 
									if ($(this).find("label").attr("class") == "partition"){
										base = $(this).children("a").html();
										return false;
									}
								});
							}
//							$.post("index.php", {mod: 'imagePlugin', action: 'init', 'base': base, 'inode': $(n).find("label").attr("rel")}, function(msg){ 
//								$("#content").html(msg);
/*								var ifrm = document.createElement("iframe");
								ifrm.setAttribute("name", "imagePlugin");
								ifrm.setAttribute("id", "imagePlugin");
								ifrm.setAttribute("src", "index.php?plugin=imagePlugin&base="+base+"&inode="+$(n).find("label").attr("rel"));
								ifrm.style.width.value = "100%";
								ifrm.style.height.value = "100%";
								$('#content').appendChild(ifrm);*/
//								return 1;
//							});
							var frm = '<iframe id="imagePlugin" style="width:100%;height:95%;border:0px;" src="index.php?plugin=imagePlugin&action=init&base='+base+'&inode='+$(n).find("label").attr("rel")+'>';
							//alert(frm);
							$("#content").html(frm);
						},
					},
				},
			},
		}
	});
}


 
/* * * * *
 * MAIN  *
 * * * * */

$(document).ready( function() {
	writeLOG('Building layout...');
	myLayout = $('body').layout({ 
		applyDefaultStyles: true,
		north__applyDefaultStyles: false,
		north__resizable: false,
		north__border: 0,
		north__spacing_open: 0,
		south__initClosed: true,
		south__size: 155,
		east__initClosed: true,
		west__resizable: true,
		west__border: 4,
		west__maxSize: 400,
		center__onresize: "adapt"
	});
	writeLOG('Finished building layout!');
	
	hmenu();
	
//	writeLOG('Building Navigation Tree...');
//	$('#casetree').tree({mod: "casetree"});
//	writeLOG('Finished building Navigation Tree!');

	loadCaseManager();
//	curCase='100102';
//	devtree(curCase);
//	showQueue();

	writeLOG('<span style="color:#00A000">Finished starting up!</span> RWA is ready.');
});
